//
//  NSObject+Addition.m
//  跨界收
//
//  Created by Dongfuming on 2018/11/19.
//  Copyright © 2018 gztx. All rights reserved.
//

#import "NSObject+Addition.h"

@implementation NSObject (Addition)

+ (instancetype)objectFromDisk
{
    NSString *dataFilePath = [self getDataFilePath];
    NSData *data = [NSData dataWithContentsOfFile:dataFilePath];
    NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
    id obj = [unarchiver decodeObjectForKey:NSStringFromClass(self.class)];
    return obj;
}

- (void)saveToDisk
{
    NSMutableData *data = [NSMutableData data];
    NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
    [archiver encodeObject:self forKey:NSStringFromClass(self.class)];
    [archiver finishEncoding];
    
    NSString *dataFilePath = [self.class getDataFilePath];
    [data writeToFile:dataFilePath atomically:YES];
}

- (void)deleteFromDisk
{
    NSString *dataFilePath = [self.class getDataFilePath];
    [self removeDataWithPath:dataFilePath];
}

#pragma mark - Helper
+ (NSString *)getDataFilePath
{
    NSString *homePath = NSHomeDirectory();
    NSString *documentPath = [homePath stringByAppendingPathComponent:@"Documents"];
    NSString *fileName = [NSStringFromClass(self.class) stringByAppendingString:@".data"];
    NSString *dataFilePath = [documentPath stringByAppendingPathComponent:fileName];
    
    return dataFilePath;
}

- (void)removeDataWithPath:(NSString *)dataPath
{
    NSFileManager *manager = [NSFileManager defaultManager];
    if ([manager fileExistsAtPath:dataPath]) {
        [manager removeItemAtPath:dataPath error:nil];
    }
}

@end
